<template>
  <div class="task">
    <!-- <h2>任务管理--开发中勿操作</h2> -->
    <el-form :inline="true"
             :model="dataForm"
             @keyup.enter.native="getDataList()">
      <el-form-item prop="taskName">
        <el-input v-model="dataForm.taskName"
                  style="width: 330px"
                  placeholder="请输入任务名称、任务编号、合同类型"
                  clearable></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 搜素按钮 -->
        <el-button type="primary"
                   icon="el-icon-search"
                   @click="search()"></el-button>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="timeInterval"
                        type="daterange"
                        range-separator="-"
                        value-format="yyyy-MM-dd"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.status"
                   clearable
                   placeholder="请选择任务状态">
          <el-option v-for="item in options"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="reset">重置</el-button>
        <el-button type="primary"
                   v-if="isAuth('sys:task:save')"
                   @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
      <el-form-item>

        <div class="file"
             v-if="isAuth('sys:task:import')">
          <el-upload class="upload-demo"
                     :action="action"
                     :before-upload="beforeAvatarUpload"
                     :on-success="handleAvatarSuccess"
                     :headers='headers'
                     :show-file-list='false'
                     multiple
                     :limit="1"
                     :file-list="fileList">
            <el-button type="info"
                       class="btnColor">导入</el-button>
          </el-upload>
        </div>
        <!-- <el-button type="info"
                   @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除</el-button> -->
      </el-form-item>
      <el-form-item>
        <el-button type="info"
                   class="btnColor"
                   v-if="isAuth('sys:task:export')"
                   :disabled="tableData.length <= 0"
                   @click="export2Excel()">导出</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格开始 -->
    <el-table :data="tableData"
              border
              v-loading="dataListLoading"
              @selection-change="selectionChangeHandle"
              style="width: 100%">
      <!-- <el-table-column type="selection"
                       header-align="center"
                       align="center"
                       width="50">
      </el-table-column> -->
      <el-table-column prop="id"
                       fixed
                       header-align="center"
                       align="center"
                       width="72"
                       label="ID">
      </el-table-column>
      <el-table-column prop="taskName"
                       header-align="center"
                       align="center"
                       width="180"
                       label="任务名称">
      </el-table-column>
      <el-table-column prop="taskNo"
                       header-align="center"
                       align="center"
                       width="170"
                       label="任务编号">
      </el-table-column>
      <el-table-column prop="description"
                       header-align="center"
                       align="center"
                       width="450"
                       label="任务描述">
      </el-table-column>
      <el-table-column prop="demand"
                       header-align="center"
                       align="center"
                       width="450"
                       label="任务要求">
      </el-table-column>
      <el-table-column prop="otherDescription"
                       header-align="center"
                       align="center"
                       width="450"
                       label="任务其他描述">
      </el-table-column>
      <!-- <el-table-column prop="mobile"
                       header-align="center"
                       align="center"
                       width="160"
                       label="手机号码">
      </el-table-column>
      <el-table-column prop="personName"
                       header-align="center"
                       align="center"
                       width="160"
                       label="姓名">
      </el-table-column> -->
      <el-table-column prop="contractNo"
                       header-align="center"
                       align="center"
                       width="160"
                       label="合同类型">
      </el-table-column>
      <el-table-column prop="taskTime"
                       header-align="center"
                       width="207"
                       align="center"
                       label="发布时间">
      </el-table-column>
      <el-table-column prop="deadTime"
                       header-align="center"
                       width="207"
                       align="center"
                       label="截止时间">
      </el-table-column>
      <el-table-column prop="personCount"
                       header-align="center"
                       align="center"
                       width="100"
                       label="任务人数">
      </el-table-column>
      <el-table-column prop="status"
                       header-align="center"
                       align="center"
                       width="180"
                       label="任务状态">
        <template slot-scope="scope">
          <!-- <el-button type="primary"
                     size="mini">确认</el-button> -->
          <span v-if="userRoleId!='1' && scope.row.status==1">待审核</span>
          <el-button v-if="userRoleId==1 && scope.row.status==1"
                     @click="audit(scope.row.id, 'Y')">通过</el-button>
          <!-- <el-button v-if="userRoleId==1 && scope.row.status==1"
                     @click="audit(scope.row.id, 'N')">驳回</el-button> -->
          <el-button v-if="userRoleId==1 && scope.row.status==1"
                     @click="audits(scope.row.id,'N')">驳回</el-button>
          <!-- 分割线/task/name-list/audit -->
          <span v-if="scope.row.status==2">审核不通过</span>
          <!-- {{scope.row.status}} -->
          <span v-if="scope.row.status==3 && userRoleId!=2">待承揽</span>
          <el-button v-if="userRoleId==2 && scope.row.status==3"
                     @click="workerConfirm(scope.row.id)">承揽</el-button>
          <!-- 分隔线 -->
          <span v-if="scope.row.status==4">待领取</span>
          <span v-if="scope.row.status==5">个人已承接</span>
        </template>
      </el-table-column>
      <el-table-column prop="taxCategories"
                       header-align="center"
                       width="150"
                       fixed="right"
                       align="center"
                       label="内置任务名单">
        <template slot-scope="scope">
          <el-button size="mini"
                     v-if="scope.row.isExits && scope.row.status>3"
                     @click="compileInternal(scope.row.taskNo,scope.row.taskName)">编辑</el-button>
          <el-button size="mini"
                     v-if="scope.row.isExits && scope.row.status>3"
                     @click="lookInternal(scope.row.taskNo,scope.row.taskName)">查看</el-button>
          <el-button v-if="scope.row.isExits==0 && scope.row.status>3 "
                     @click="compileInternal(scope.row.taskNo,scope.row.taskName)"
                     size="mini">上传内置名单</el-button>
          <!-- <el-tooltip class="item"
                      effect="dark"
                      :content="scope.row.backMsg"
                      placement="top"
                      v-if="scope.row.status==2">
            <el-button>查看驳回原因</el-button>
          </el-tooltip> -->
          <el-button v-if="scope.row.status==2"
                     @click="backMsgs(scope.row.backMsg)">查看驳回原因</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       fixed="right"
                       v-if="isAuth('sys:task:update') || isAuth('sys:task:delete')"
                       width="150">
        <template slot-scope="scope">
          <el-button @click="update(scope.row.id)"
                     type="text"
                     v-if="isAuth('sys:task:update')"
                     size="small">修改</el-button>
          <el-button type="text"
                     size="small"
                     v-if="isAuth('sys:task:delete')"
                     @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <!-- 分页前说明 -->
      <div class="instructions">显示第{{tableData.length>0?((pageIndex-1)*pageSize+1):0}}到第{{(pageIndex-1)*pageSize+tableData.length}}条数据，总共{{totalPage}}条数据
        <!-- ，每页显示 -->
        <!-- 条数据 -->
      </div>
      <!-- 分页 -->
      <el-pagination @size-change="sizeChangeHandle"
                     @current-change="currentChangeHandle"
                     :current-page="pageIndex"
                     :page-sizes="[10, 20, 50]"
                     :page-size="pageSize"
                     :total="totalPage"
                     layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <!-- 分页2 -->
    </div>

    <!-- 弹窗, 新增 / 修改 -->
    <addTask v-if="addOrUpdateVisible"
             ref="addOrUpdate"
             @refreshDataList="getDataList"></addTask>
    <addInternalList v-if="addInternalListVisible"
                     ref="addInternalList"
                     @refreshDataList="getDataList"></addInternalList>
    <!-- 驳回 -->
    <reject v-if="rejectVisible"
            ref="reject"
            @refreshDataList="getDataList" />
    <!-- 驳回理由 -->
    <el-dialog title="驳回理由:"
               :visible.sync="dialogVisible"
               width="20%">
      <span>{{oneBackMsg}}</span>
      <span slot="footer"
            class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
        <el-button type="primary"
                   @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import addTask from './add/addTask'
import addInternalList from './add/addInternalList'
import reject from './add/reject'
export default {
  data () {
    return {
      dataForm: {
        taskName: '',
        status: ''
      },
      headers: {
        token: ''
      },
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      addInternalListVisible: false,
      rejectVisible: false,
      // 时间区间,开始，结束时间
      timeInterval: '',
      startTime: '',
      endTime: '',
      // 假数据
      tableData: [],
      // 上传相关
      fileList: [],
      action: '',
      // 应该没用
      companyId: '',
      // 用户确认状态
      options: [
        {
          value: 1,
          label: '待审核'
        },
        {
          value: 2,
          label: '审核不通过'
        },
        {
          value: 3,
          label: '待承揽'
        },
        {
          value: 4,
          label: '公司已承接'
        },
        {
          value: 5,
          label: '个人已承接'
        }
      ],
      // 用户类型
      userRoleId: '',
      // 驳回理由
      msg: '',
      dialogVisible: false,
      oneBackMsg: ''
    }
  },
  components: {
    addTask,
    addInternalList,
    reject
  },
  activated () {
    // 上传地址
    this.action = this.$baseUrl + '/sys/task/import'
    this.headers.token = this.$cookie.get('token')
    // 获取用户类型
    this.userRoleId = sessionStorage.getItem('userRoleId')
    this.getDataList()
  },
  watch: {
    timeInterval () {
      try {
        this.startTime = this.timeInterval[0]
        this.endTime = this.timeInterval[1]
      } catch (error) {
        this.startTime = ''
        this.endTime = ''
      }
      this.getDataList()
    },
    // 监听用户确认状态变化
    'dataForm.status' () {
      this.pageIndex = 1
      this.getDataList()
    }
  },
  methods: {
    // 获取数据列表
    async getDataList () {
      this.dataListLoading = true
      await this.$http({
        url: this.$http.adornUrl('/sys/task/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'startTime': this.startTime,
          'endTime': this.endTime,
          'status': this.dataForm.status || '',
          'taskName': this.dataForm.taskName
        })
      }).then(({ data }) => {
        this.dataListLoading = false
        this.tableData = data.page.list
        this.totalPage = data.page.totalCount
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增
    addOrUpdateHandle () {
      // 显示
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.mode = 'add'
        if (sessionStorage.getItem('userRoleId') === '2') {
          this.companyId = this.$store.state.user.id
        }
        this.$refs.addOrUpdate.ReTime = []
        this.$refs.addOrUpdate.dataForm = {
          cid: this.companyId,
          taskName: '',
          description: '',
          personCount: '',
          demand: '',
          otherDescription: '',
          mobile: '',
          personName: '',
          contractNo: '',
          taskTime: '',
          deadTime: '',
          receiveState: ''
        }
        this.$refs.addOrUpdate.addInit()
      })
    },
    // 编辑
    update (id) {
      // 显示
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.mode = 'edit'
        this.$refs.addOrUpdate.visible = true
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/task/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.pageIndex = 1
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => { })
    },
    // 接下来
    // 上传前
    beforeAvatarUpload (f) {
      if (!(f.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || f.type === 'application/vnd.ms-excel')) {
        this.$message.error('上传文件只能是 xls和xlsx 格式!')
        return false
      } else {
        return true
      }
    },
    // 导入成功处理函数
    handleAvatarSuccess (res, file) {
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.pageIndex = 1
        this.getDataList()
      } else {
        this.$message.error(res.msg)
      }
      this.fileList = []
    },
    // 导出函数
    export2Excel () {
      this.$http({
        url: this.$http.adornUrl('/sys/task/export'),
        method: 'post',
        responseType: 'blob',
        data: this.$http.adornParams({
          // 'startTime': this.startTime,
          // 'endTime': this.endTime,
          // 'taskName': this.dataForm.taskName
          'startTime': this.startTime,
          'endTime': this.endTime,
          'status': this.dataForm.status || '',
          'taskName': this.dataForm.taskName
        })
      }).then((_res) => {
        let blob = new Blob([_res.data], {
          type: 'application/vnd.ms-excel'
        })
        let url = window.URL.createObjectURL(blob)
        let a = document.createElement('a')
        a.href = url
        // document.body.appendChild(a)
        // window.open()
        a.download = '任务管理.xlsx'
        a.click()
        window.URL.revokeObjectURL(a.href)
      })
    },
    // 按钮搜索
    search () {
      this.pageIndex = 1
      this.getDataList()
    },
    // 重置
    reset () {
      this.pageIndex = 1
      this.dataForm.taskName = ''
      this.timeInterval = ''
      this.dataForm.status = ''
      this.getDataList()
    },
    // 内置任务列表
    // 编辑
    compileInternal (taskNo, taskName) {
      // 显示
      this.addInternalListVisible = true
      this.$nextTick(() => {
        this.$refs.addInternalList.mode = 'add'
        this.$refs.addInternalList.addListVisble = false
        this.$refs.addInternalList.addList = {
          userName: '',
          moblie: ''
        }
        this.$refs.addInternalList.nameList = {}
        this.$refs.addInternalList.init(taskNo, taskName)
      })
    },
    // 查看
    lookInternal (taskNo, taskName) {
      // 显示
      this.addInternalListVisible = true
      this.$nextTick(() => {
        this.$refs.addInternalList.mode = 'edit'
        this.$refs.addInternalList.addListVisble = false
        this.$refs.addInternalList.addList = {
          userName: '',
          moblie: ''
        }
        this.$refs.addInternalList.nameList = {}
        this.$refs.addInternalList.init(taskNo, taskName)
      })
    },
    async audit (id, isPass) {
      if (isPass === 'Y') {
        this.msg = '成功通过'
      }
      await this.$http({
        url: this.$http.adornUrl('/task/name-list/audit'),
        method: 'get',
        params: this.$http.adornParams({
          id,
          isPass,
          message: this.msg
        })
      }).then(({ data }) => {
        // this.pageIndex = 1
        // this.getDataList()
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              // this.pageIndex = 1
              this.getDataList()
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    async workerConfirm (id) {
      await this.$http({
        url: this.$http.adornUrl('/task/name-list/accept'),
        method: 'get',
        params: this.$http.adornParams({
          id
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.pageIndex = 1
              this.getDataList()
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 驳回
    audits (id, isPass) {
      // 显示
      this.rejectVisible = true
      this.$nextTick(() => {
        this.$refs.reject.visible = true
        this.$refs.reject.auditInit(id, isPass)
      })
    },
    // 驳回理由弹出层
    backMsgs (oneMsg) {
      this.dialogVisible = true
      this.oneBackMsg = oneMsg
    }
  }
}
</script>

<style lang="scss" scoped>
.task {
  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .instructions {
      height: 19px;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      line-height: 19px;
      color: #333333;
    }
  } // 导入
  button.el-button.btnColor.el-button--info.el-button--medium {
    position: relative;
    overflow: hidden;
  }
  .file {
    display: inline;
    position: relative;
    overflow: hidden;
    .fileBtn {
      opacity: 0;
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
    .upload-demo {
      display: inherit;
    }
  }
}
</style>